<template>
  <div class="list-header">
    <div class="header-button" v-if="hasAuth(AUTH_CODE.FIELD_ACTION.ADD)">
      <u-button type="primary" @click="handleEdit()">
        新建模板
      </u-button>
    </div>
    <dynamics-filter
      label-width="auto"
      :wrapper-width="250"
      :setting="setting"
      :loading="listQuery.loading"
      @query="handleQuery"
    />
  </div>
  <div class="list-body">
    <div class="list-wrap">
      <u-table
        row-key="variableId"
        show-pagination
        :data="listData"
        :columns="fieldColumns"
        :loading="listQuery.loading"
        :pagination="{
          total: listQuery.total,
          current: listQuery.currentPage,
          pageSize: listQuery.pageSize,
          showTotal: true,
          showSizer: true,
          showElevator: true
        }"
        @change="handleTableChange"
      >
        <template #variableName="{ row }">
          <one-line-text :text="row.variableName" />
        </template>
        <template #variableType="{ row }">
          {{ fieldTypes.find(a => a.value === row.variableType)?.label }}
        </template>
        <template #usedStrategy="{ row }">
          <one-line-text :text="getUsedStrategy(row.usedStrategy)" />
        </template>
        <template #status="{ row }">
          {{ filter("status", row.status) }}
        </template>
        <template #createTime="{ row }">
          {{ parseTime(row.createTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #updateTime="{ row }">
          {{ parseTime(row.updateTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #remark="{ row }">
          <one-line-text :text="row.remark" />
        </template>
        <template #action="{ row }">
          <u-tooltip title="查看" v-if="hasAuth(AUTH_CODE.FIELD_ACTION.VIEW)">
            <u-button
              type="text"
              icon="view-detail"
              class="m-r-1 action-button"
              @click="handleView(row)"
            />
          </u-tooltip>
          <u-tooltip
            title="编辑"
            v-if="row.variableType === 2 && hasAuth(AUTH_CODE.FIELD_ACTION.EDIT)"
          >
            <u-button
              type="text"
              icon="edit"
              class="m-r-1 action-button"
              :disabled="!!(row.usedStrategy && row.usedStrategy.length)"
              @click="handleEdit(row)"
            />
          </u-tooltip>
          <u-pop-confirm
            v-if="
              row.status === 1 && row.variableType === 2 && hasAuth(AUTH_CODE.FIELD_ACTION.ENABLE)
            "
            title="确定禁用模板?"
            cancel-text="取消"
            ok-text="确认"
            placement="left"
            @confirm="handleForbid(row, 2)"
          >
            <u-tooltip title="禁用">
              <u-button
                type="text"
                icon="forbid"
                class="m-r-1 action-button"
                :disabled="!!(row.usedStrategy && row.usedStrategy.length)"
              />
            </u-tooltip>
          </u-pop-confirm>
          <u-pop-confirm
            v-if="
              row.status === 2 && row.variableType === 2 && hasAuth(AUTH_CODE.FIELD_ACTION.ENABLE)
            "
            title="确定启用模板?"
            cancel-text="取消"
            ok-text="确认"
            placement="left"
            @confirm="handleForbid(row, 1)"
          >
            <u-tooltip title="启用">
              <u-button type="text" icon="play" class="m-r-1 action-button" />
            </u-tooltip>
          </u-pop-confirm>
          <u-tooltip
            title="复制"
            v-if="row.variableType === 2 && hasAuth(AUTH_CODE.FIELD_ACTION.COPY)"
          >
            <u-button
              type="text"
              icon="copy"
              class="m-r-1 action-button"
              @click="handleCopy(row)"
            />
          </u-tooltip>
          <u-pop-confirm
            v-if="row.variableType === 2 && hasAuth(AUTH_CODE.FIELD_ACTION.DELETE)"
            title="确定删除?"
            cancel-text="取消"
            ok-text="确认"
            placement="left"
            @confirm="handleDelete(row)"
          >
            <u-tooltip title="删除">
              <u-button
                type="text"
                icon="delete"
                class="action-button"
                :disabled="row.status === 1"
              />
            </u-tooltip>
          </u-pop-confirm>
        </template>
      </u-table>
    </div>
  </div>
</template>
<script>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  message, DynamicsFilter, libs, hooks
} from '@bairong/vix'
import { getFieldListApi, changeStatusApi, deleteFieldApi } from '@api/field'
import { status } from '@libs/data/enums'
import OneLineText from '@C/OneLineText.vue'
import AUTH_CODE from '@libs/data/const'
import filter from '@/filter'
import { fieldColumns } from '../columns'

const { usePageList, usePermission } = hooks
const { parseTime } = libs.conversion

export default {
  name: 'FieldList',
  components: { DynamicsFilter, OneLineText },
  setup() {
    const store = useStore()
    const { hasAuth } = usePermission()
    const setting = [
      {
        name: 'variableName',
        label: '模板名称',
        type: 'input',
        placeholder: '请输入模板名称'
      },
      {
        name: 'status',
        label: '状态',
        type: 'select',
        options: status
      }
    ]
    const fieldTypes = ref([])
    const router = useRouter()

    const {
      listData, listQuery, getList, handleQuery, handlePageChange
    } = usePageList({
      getListApi: getFieldListApi,
      getQueryParameters: DynamicsFilter.libs.getQueryParameters
    })

    const handleEdit = row => {
      if (row === undefined) {
        router.push({
          path: '/marketing/fieldAdd'
        })
        return
      }
      router.push({
        path: '/marketing/fieldEdit',
        query: {
          variableId: row.variableId
        }
      })
    }

    const handleView = row => {
      router.push({
        path: '/marketing/fieldDetail',
        query: {
          variableId: row.variableId
        }
      })
    }

    // eslint-disable-next-line no-shadow
    const handleForbid = (row, status) => {
      listQuery.loading = true
      const msg = status === 1 ? '启用' : '禁用'
      changeStatusApi({ status, variableId: row.variableId })
        .then(() => {
          message.success(`${msg}模板成功`)
          getList()
        })
        .catch(err => {
          message.error(err)
          listQuery.loading = false
        })
    }

    const handleCopy = row => {
      router.push({
        path: '/marketing/fieldCopy',
        query: {
          variableId: row.variableId
        }
      })
    }

    const handleDelete = row => {
      const { variableId } = row
      listQuery.loading = true
      deleteFieldApi({ variableId })
        .then(() => {
          message.success('删除模板成功')
          getList()
        })
        .catch(err => {
          message.error(err)
          listQuery.loading = false
        })
    }

    const handleTableChange = pagination => {
      const { current, pageSize, total } = pagination
      let nextCurrent = current
      if ((current - 1) * pageSize > total) {
        nextCurrent = Math.floor(total / pageSize) + 1
      }
      handlePageChange(nextCurrent, pageSize)
    }

    onMounted(() => {
      getList()
      store.dispatch('getFieldModelTypes').then(res => {
        fieldTypes.value = res
      })
    })

    const getUsedStrategy = str => {
      if (str) {
        return str.join(',')
      }
      return ''
    }

    return {
      AUTH_CODE,
      hasAuth,
      setting,
      listData,
      listQuery,
      fieldColumns,
      handleQuery,
      handleEdit,
      handleView,
      handleForbid,
      handleCopy,
      handleDelete,
      parseTime,
      filter,
      handleTableChange,
      fieldTypes,
      getUsedStrategy
    }
  }
}
</script>
<style lang="less"></style>
